package com.itheima.wisdomnext.mapper;

import com.itheima.wisdomnext.entity.Like;
import org.apache.ibatis.annotations.*;

@Mapper
public interface LikeMapper {

    // 插入一条点赞记录
    @Insert("INSERT INTO likes (userid, target_id, target_type) VALUES (#{userid}, #{targetId}, #{targetType})")
    int insertLike(Like like);

    //增加帖子的点赞数
    @Update("UPDATE posts SET likes = likes + 1 WHERE id = #{targetId}")
    int incrementPostLikes(int targetId);

    //增加评论的点赞数
    @Update("UPDATE comments SET likes = likes + 1 WHERE id = #{targetId}")
    int incrementCommentLikes(int targetId);

    // 根据用户ID、目标ID和目标类型删除点赞记录
    @Delete("DELETE FROM likes WHERE userid = #{userid} AND target_id = #{targetId} AND target_type = #{targetType}")
    int deleteLike(Like like);

    //减少帖子的点赞数
    @Update("UPDATE posts SET likes = likes - 1 WHERE id = #{targetId} AND likes > 0")
    int decrementPostLikes(int targetId);

    //减少评论点赞数
    @Update("UPDATE comments SET likes = likes - 1 WHERE id = #{targetId} AND likes > 0")
    int decrementCommentLikes(int targetId);

    // 根据用户ID、目标ID和目标类型查询点赞记录
    @Select("SELECT * FROM likes WHERE userid = #{userid} AND target_id = #{targetId} AND target_type = #{targetType}")
    Like selectLike(Like like);

    // 判断用户是否对指定的帖子点赞
    @Select("SELECT COUNT(*) FROM likes WHERE target_id = #{postId} AND target_type = 'POST' AND userid = #{userId}")
    boolean isPostLikedByUser(@Param("postId") Long postId, @Param("userId") Long userId);

    // 查询点赞了该用户帖子的人数
    @Select("SELECT COUNT(*) FROM likes WHERE target_id IN (SELECT id FROM posts WHERE userid = #{userId})")
    int countLikesByUserId(int userId);
}
